<script setup lang="ts">
import { computed, ref, onMounted, watch } from "vue";
import type { Question, QuestionStatus } from "../../../types/question";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getQuestions,
  createQuestion,
  updateQuestion,
  deleteQuestion,
  toggleQuestionStatus,
} from "../../../api/question";

const questions = ref<Question[]>([]);
const total = ref(0);
const loading = ref(false);
const searchKeyword = ref("");
const statusFilter = ref<QuestionStatus | "all">("all");

const showAddDialog = ref(false);
const showEditDialog = ref(false);

const editingQuestion = ref<Question | null>(null);

const addForm = ref({
  title: "",
});

const editForm = ref({
  title: "",
  status: "active" as QuestionStatus,
});

const formErrors = ref({
  title: "",
});

const statusLabelMap: Record<QuestionStatus, string> = {
  active: "启用",
  inactive: "停用",
};

const statusFilterOptions = [
  { label: "全部状态", value: "all" },
  { label: "已启用", value: "active" },
  { label: "已停用", value: "inactive" },
];

const filteredQuestions = computed(() => {
  return questions.value;
});

// 监听搜索关键词和状态筛选
watch([searchKeyword, statusFilter], () => {
  loadQuestions();
});

// 加载问题列表
const loadQuestions = async () => {
  try {
    loading.value = true;
    const params: any = {
      skip: 0,
      limit: 100,
    };

    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim();
    }

    if (statusFilter.value !== "all") {
      params.status = statusFilter.value;
    }

    const response = await getQuestions(params);
    questions.value = response.questions;
    total.value = response.total;
  } catch (error: any) {
    ElMessage.error(error || "加载问题列表失败");
  } finally {
    loading.value = false;
  }
};

// 初始化加载
onMounted(() => {
  loadQuestions();
});

const resetAddForm = () => {
  addForm.value = {
    title: "",
  };
  formErrors.value = { title: "" };
};

const resetEditForm = () => {
  editForm.value = {
    title: "",
    status: "active",
  };
  formErrors.value = { title: "" };
};

const openAddDialog = () => {
  resetAddForm();
  showAddDialog.value = true;
};

const closeAddDialog = () => {
  showAddDialog.value = false;
};

const openEditDialog = (question: Question) => {
  editingQuestion.value = { ...question };
  editForm.value = {
    title: question.title,
    status: question.status,
  };
  formErrors.value = { title: "" };
  showEditDialog.value = true;
};

const closeEditDialog = () => {
  showEditDialog.value = false;
  editingQuestion.value = null;
  resetEditForm();
};

const validateForm = (payload: { title: string }) => {
  const errors = { title: "" };
  let isValid = true;

  if (!payload.title.trim()) {
    errors.title = "问题标题不能为空";
    isValid = false;
  } else if (payload.title.length < 4) {
    errors.title = "问题标题至少4个字符";
    isValid = false;
  }

  formErrors.value = errors;
  return isValid;
};

const addQuestionHandler = async () => {
  if (!validateForm(addForm.value)) {
    return;
  }

  try {
    loading.value = true;
    await createQuestion({
      title: addForm.value.title.trim(),
    });
    closeAddDialog();
    await loadQuestions();
  } catch (error: any) {
    ElMessage.error(error || "创建问题失败");
  } finally {
    loading.value = false;
  }
};

const saveEdit = async () => {
  if (!editingQuestion.value) {
    return;
  }

  if (!validateForm(editForm.value)) {
    return;
  }

  try {
    loading.value = true;
    await updateQuestion(editingQuestion.value.id, {
      title: editForm.value.title.trim(),
      status: editForm.value.status,
    });
    closeEditDialog();
    await loadQuestions();
  } catch (error: any) {
    ElMessage.error(error || "更新问题失败");
  } finally {
    loading.value = false;
  }
};
const deleteQuestionHandler = async (questionId: number) => {
  ElMessageBox.confirm("确定要删除这个问题吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      loading.value = true;
      await deleteQuestion(questionId);
      await loadQuestions();
    } catch (error: any) {
      ElMessage.error(error || "删除问题失败");
    } finally {
      loading.value = false;
    }
  });
};

const toggleQuestionStatusHandler = async (questionId: number) => {
  try {
    loading.value = true;
    await toggleQuestionStatus(questionId);
    await loadQuestions();
  } catch (error: any) {
    ElMessage.error(error || "切换问题状态失败");
  } finally {
    loading.value = false;
  }
};

const statusBadgeClass = (status: QuestionStatus) =>
  status === "active"
    ? "status-badge status-active"
    : "status-badge status-inactive";

const toggleButtonLabel = (status: QuestionStatus) =>
  status === "active" ? "停用" : "启用";
</script>

<template>
  <div class="questions-container">
    <div class="questions-header">
      <h1>问题管理</h1>
      <div class="header-actions">
        <div class="search-box">
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索问题标题..."
          />
        </div>
        <div class="status-filter">
          <select v-model="statusFilter">
            <option
              v-for="option in statusFilterOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </option>
          </select>
        </div>
        <button class="add-btn" @click="openAddDialog">
          <span class="icon">＋</span>
          新建问题
        </button>
      </div>
    </div>

    <div class="questions-content">
      <div class="table-container">
        <table class="questions-table">
          <thead>
            <tr>
              <th>问题与背景</th>
              <th>使用次数</th>
              <th>状态</th>
              <th>更新时间</th>
              <th class="actions-column">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="question in filteredQuestions" :key="question.id">
              <td>
                <div class="question-title">{{ question.title }}</div>
              </td>
              <td>
                <span class="usage-count">{{ question.usage_count || 0 }}</span>
              </td>
              <td>
                <span :class="statusBadgeClass(question.status)">
                  {{ statusLabelMap[question.status] }}
                </span>
              </td>
              <td>
                {{ new Date(question.updated_at).toLocaleString("zh-CN") }}
              </td>
              <td class="actions">
                <button class="edit-btn" @click="openEditDialog(question)">
                  编辑
                </button>
                <button
                  class="toggle-btn"
                  @click="toggleQuestionStatusHandler(question.id)"
                >
                  {{ toggleButtonLabel(question.status) }}
                </button>
                <button
                  class="delete-btn"
                  @click="deleteQuestionHandler(question.id)"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <div v-if="filteredQuestions.length === 0" class="empty-state">
          <p>没有找到匹配的问题</p>
          <span class="empty-tip">尝试调整搜索条件或创建一个新问题</span>
        </div>
      </div>
    </div>

    <div v-if="showAddDialog" class="dialog-overlay" @click="closeAddDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>新建问题</h2>
          <button class="close-btn" @click="closeAddDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label for="add-title">问题标题</label>
            <input
              id="add-title"
              v-model="addForm.title"
              :class="{ error: formErrors.title }"
              type="text"
              placeholder="如：诺基亚在5G领域的核心竞争力是什么?"
            />
            <span v-if="formErrors.title" class="error-message">{{
              formErrors.title
            }}</span>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeAddDialog">取消</button>
          <button class="confirm-btn" @click="addQuestionHandler">创建</button>
        </div>
      </div>
    </div>

    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>编辑问题</h2>
          <button class="close-btn" @click="closeEditDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label for="edit-title">问题标题</label>
            <input
              id="edit-title"
              v-model="editForm.title"
              :class="{ error: formErrors.title }"
              type="text"
              placeholder="更新问题标题"
            />
            <span v-if="formErrors.title" class="error-message">{{
              formErrors.title
            }}</span>
          </div>
          <div class="form-group">
            <label for="edit-status">状态</label>
            <select id="edit-status" v-model="editForm.status">
              <option value="active">启用</option>
              <option value="inactive">停用</option>
            </select>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeEditDialog">取消</button>
          <button class="confirm-btn" @click="saveEdit">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.questions-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: transparent;
  position: relative;
}

.questions-header {
  padding: 24px 32px;
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.08) 0%,
    rgba(49, 190, 255, 0.03) 100%
  );
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(49, 190, 255, 0.2);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 28px;
    font-weight: 600;
    color: #f6f9fe;
    font-family: "YouSheBiaoTiHei", sans-serif;
    text-shadow: 0 2px 8px rgba(49, 190, 255, 0.3);
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-box {
  position: relative;

  input {
    width: 320px;
    padding: 10px 44px 10px 16px;
    background: rgba(26, 31, 58, 0.6);
    border: 1px solid rgba(49, 190, 255, 0.3);
    border-radius: 8px;
    font-size: 14px;
    color: #f6f9fe;
    font-family: "Alibaba PuHuiTi", sans-serif;
    transition: all 0.3s ease;

    &::placeholder {
      color: rgba(246, 249, 254, 0.5);
    }

    &:focus {
      border-color: rgba(49, 190, 255, 0.6);
      outline: none;
      background: rgba(26, 31, 58, 0.8);
      box-shadow: 0 0 0 3px rgba(49, 190, 255, 0.15),
        0 4px 12px rgba(49, 190, 255, 0.2);
    }
  }

  .search-icon {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 16px;
    color: rgba(246, 249, 254, 0.6);
  }
}

.status-filter {
  select {
    width: 160px;
    padding: 10px 14px;
    background: rgba(26, 31, 58, 0.6);
    border: 1px solid rgba(49, 190, 255, 0.3);
    border-radius: 8px;
    font-size: 14px;
    color: #f6f9fe;
    font-family: "Alibaba PuHuiTi", sans-serif;
    transition: all 0.3s ease;

    &:focus {
      border-color: rgba(49, 190, 255, 0.6);
      outline: none;
      background: rgba(26, 31, 58, 0.8);
      box-shadow: 0 0 0 3px rgba(49, 190, 255, 0.15),
        0 4px 12px rgba(49, 190, 255, 0.2);
    }
  }
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.25) 0%,
    rgba(49, 190, 255, 0.15) 100%
  );
  border: 1px solid rgba(49, 190, 255, 0.4);
  border-radius: 8px;
  color: #31beff;
  font-size: 14px;
  font-weight: 500;
  font-family: "Alibaba PuHuiTi", sans-serif;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(49, 190, 255, 0.2);

  .icon {
    font-size: 18px;
  }

  &:hover {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.35) 0%,
      rgba(49, 190, 255, 0.25) 100%
    );
    border-color: rgba(49, 190, 255, 0.6);
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(49, 190, 255, 0.3);
  }

  &:active {
    transform: translateY(0);
  }
}

.questions-content {
  flex: 1;
  overflow: auto;
  padding: 24px 32px 32px;
  position: relative;
}

.table-container {
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.05) 0%,
    rgba(49, 190, 255, 0.02) 100%
  );
  backdrop-filter: blur(20px);
  border: 1px solid rgba(49, 190, 255, 0.15);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.questions-table {
  width: 100%;
  border-collapse: collapse;

  thead {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.15) 0%,
      rgba(49, 190, 255, 0.08) 100%
    );

    th {
      padding: 16px 20px;
      text-align: left;
      font-size: 14px;
      font-weight: 600;
      color: rgba(49, 190, 255, 0.9);
      font-family: "Alibaba PuHuiTi", sans-serif;
      border-bottom: 1px solid rgba(49, 190, 255, 0.2);
    }
  }

  tbody {
    tr {
      transition: all 0.3s ease;

      &:hover {
        background: rgba(49, 190, 255, 0.08);
        box-shadow: inset 0 0 20px rgba(49, 190, 255, 0.1);
      }

      td {
        padding: 16px 20px;
        font-size: 14px;
        color: rgba(246, 249, 254, 0.85);
        font-family: "Alibaba PuHuiTi", sans-serif;
        border-bottom: 1px solid rgba(49, 190, 255, 0.1);
        vertical-align: middle;
      }
    }
  }
}

.question-title {
  font-size: 15px;
  font-weight: 600;
  color: #f6f9fe;
  text-shadow: 0 2px 6px rgba(49, 190, 255, 0.3);
}

.question-description {
  font-size: 13px;
  color: rgba(246, 249, 254, 0.65);
  line-height: 1.5;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 4px 10px;
  border-radius: 999px;
  background: rgba(49, 190, 255, 0.12);
  border: 1px solid rgba(49, 190, 255, 0.3);
  font-size: 12px;
  color: #31beff;
  font-family: "Alibaba PuHuiTi", sans-serif;
  box-shadow: 0 2px 8px rgba(49, 190, 255, 0.15);
}

.usage-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 48px;
  padding: 4px 12px;
  border-radius: 999px;
  font-size: 14px;
  font-weight: 600;
  color: #31beff;
  background: rgba(49, 190, 255, 0.12);
  border: 1px solid rgba(49, 190, 255, 0.3);
  box-shadow: 0 2px 8px rgba(49, 190, 255, 0.15);
}

.status-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 64px;
  padding: 4px 12px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 500;
  font-family: "Alibaba PuHuiTi", sans-serif;
  border: 1px solid transparent;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

  &.status-active {
    border-color: rgba(56, 189, 248, 0.4);
    background: rgba(56, 189, 248, 0.15);
    color: #38bdf8;
  }

  &.status-inactive {
    border-color: rgba(239, 68, 68, 0.4);
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
  }
}

.actions {
  display: flex;
  gap: 8px;

  button {
    padding: 6px 16px;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    font-family: "Alibaba PuHuiTi", sans-serif;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .edit-btn {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.2) 0%,
      rgba(49, 190, 255, 0.1) 100%
    );
    border: 1px solid rgba(49, 190, 255, 0.3);
    color: #31beff;

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(49, 190, 255, 0.3) 0%,
        rgba(49, 190, 255, 0.2) 100%
      );
      border-color: rgba(49, 190, 255, 0.5);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(49, 190, 255, 0.3);
    }
  }

  .toggle-btn {
    background: linear-gradient(
      135deg,
      rgba(139, 92, 246, 0.2) 0%,
      rgba(139, 92, 246, 0.12) 100%
    );
    border: 1px solid rgba(139, 92, 246, 0.4);
    color: #c084fc;

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(139, 92, 246, 0.3) 0%,
        rgba(139, 92, 246, 0.2) 100%
      );
      border-color: rgba(139, 92, 246, 0.6);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(139, 92, 246, 0.35);
    }
  }

  .delete-btn {
    background: linear-gradient(
      135deg,
      rgba(220, 38, 38, 0.2) 0%,
      rgba(220, 38, 38, 0.1) 100%
    );
    border: 1px solid rgba(220, 38, 38, 0.3);
    color: #ef4444;

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(220, 38, 38, 0.3) 0%,
        rgba(220, 38, 38, 0.2) 100%
      );
      border-color: rgba(220, 38, 38, 0.5);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(220, 38, 38, 0.3);
    }
  }
}

.actions-column {
  width: 240px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
  color: rgba(246, 249, 254, 0.6);

  .empty-tip {
    display: block;
    margin-top: 8px;
    font-size: 13px;
    color: rgba(246, 249, 254, 0.5);
  }
}

.dialog-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.dialog {
  background: linear-gradient(
    135deg,
    rgba(26, 31, 58, 0.95) 0%,
    rgba(10, 14, 39, 0.95) 100%
  );
  backdrop-filter: blur(20px);
  border: 1px solid rgba(49, 190, 255, 0.3);
  border-radius: 12px;
  width: 92%;
  max-width: 520px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5), 0 0 20px rgba(49, 190, 255, 0.2);
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(49, 190, 255, 0.2);
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.08) 0%,
    rgba(49, 190, 255, 0.03) 100%
  );

  h2 {
    font-size: 20px;
    font-weight: 600;
    color: #f6f9fe;
    font-family: "YouSheBiaoTiHei", sans-serif;
    text-shadow: 0 2px 8px rgba(49, 190, 255, 0.3);
  }

  .close-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    border: 1px solid transparent;
    color: rgba(246, 249, 254, 0.6);
    font-size: 28px;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(49, 190, 255, 0.1);
      border-color: rgba(49, 190, 255, 0.3);
      color: #31beff;
      transform: rotate(90deg);
    }
  }
}

.dialog-body {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(49, 190, 255, 0.9);
    font-family: "Alibaba PuHuiTi", sans-serif;
  }

  input,
  textarea,
  select {
    width: 100%;
    padding: 10px 16px;
    background: rgba(26, 31, 58, 0.6);
    border: 1px solid rgba(49, 190, 255, 0.3);
    border-radius: 8px;
    font-size: 14px;
    color: #f6f9fe;
    font-family: "Alibaba PuHuiTi", sans-serif;
    transition: all 0.3s ease;
    resize: none;

    &::placeholder {
      color: rgba(246, 249, 254, 0.4);
    }

    &:focus {
      border-color: rgba(49, 190, 255, 0.6);
      outline: none;
      background: rgba(26, 31, 58, 0.8);
      box-shadow: 0 0 0 3px rgba(49, 190, 255, 0.15),
        0 4px 12px rgba(49, 190, 255, 0.2);
    }

    &.error {
      border-color: rgba(220, 38, 38, 0.6);

      &:focus {
        box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.15),
          0 4px 12px rgba(220, 38, 38, 0.2);
      }
    }
  }

  .error-message {
    display: block;
    margin-top: 6px;
    font-size: 13px;
    color: #ef4444;
    font-family: "Alibaba PuHuiTi", sans-serif;
  }

  .form-tip {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: rgba(246, 249, 254, 0.5);
    font-family: "Alibaba PuHuiTi", sans-serif;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid rgba(49, 190, 255, 0.2);
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.03) 0%,
    rgba(49, 190, 255, 0.01) 100%
  );

  button {
    padding: 10px 24px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    font-family: "Alibaba PuHuiTi", sans-serif;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .cancel-btn {
    background: rgba(49, 190, 255, 0.08);
    border: 1px solid rgba(49, 190, 255, 0.2);
    color: rgba(246, 249, 254, 0.7);

    &:hover {
      background: rgba(49, 190, 255, 0.15);
      border-color: rgba(49, 190, 255, 0.3);
      color: #f6f9fe;
      transform: translateY(-2px);
    }
  }

  .confirm-btn {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.3) 0%,
      rgba(49, 190, 255, 0.2) 100%
    );
    border: 1px solid rgba(49, 190, 255, 0.4);
    color: #31beff;
    box-shadow: 0 2px 8px rgba(49, 190, 255, 0.2);

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(49, 190, 255, 0.4) 0%,
        rgba(49, 190, 255, 0.3) 100%
      );
      border-color: rgba(49, 190, 255, 0.6);
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(49, 190, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

@media (max-width: 1024px) {
  .header-actions {
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .questions-stats {
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  }

  .actions {
    flex-wrap: wrap;

    button {
      flex: 1 1 48%;
    }
  }
}
</style>
